import * as echarts from '../../ec-canvas/echarts';

Component({
    properties: {
        xData: {
            type: Array,
            observer(newVal) {
                // console.log('xData变化了', newVal)
                this.updateChart()
            }
        },
        yData: {
            type: Array,
            observer(newVal) {
                // console.log('yData变化了', newVal)
                this.updateChart()
            }
        },
        list: { type: Array }    // 接收父页面的其他数据
    },

    data: {
        ec: {
            lazyLoad: true, // 延迟加载
        },
    },

    lifetimes: {
        ready() {
            // 确保在 DOM 渲染完成后延迟初始化图表
            setTimeout(() => {
                this.initChart();
            }, 500); // 延迟 500ms 后初始化
        }
    },

    methods: {
        initChart() {
            const chartComponent = this.selectComponent('#myChart');
            if (!chartComponent) return;

            chartComponent.init((canvas, width, height, dpr) => {
                this.chart = echarts.init(canvas, null, {
                    width: width,
                    height: height,
                    devicePixelRatio: dpr
                });
                this.setChartOption();
                return this.chart;
            });
        },

        updateChart() {
            // 如果图表已经初始化，直接更新 option
            if (this.chart) {
                this.setChartOption();
            }
        },

        setChartOption() {
            const option = {
                grid: { right: '6%', top: '8%', bottom: '28%' },
                tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
                xAxis: {
                    type: 'category',
                    data: this.properties.xData,
                    axisLabel: { interval: 0, rotate: 30, margin: 12 },
                    axisTick: { alignWithLabel: true },
                    boundaryGap: true
                },
                yAxis: { type: 'value' },
                dataZoom: [
                    { type: 'inside', start: 0, end: 100 },
                    { type: 'slider', start: 0, end: 100 }
                ],
                series: [{
                    name: '平均分',
                    type: 'bar',
                    data: this.properties.xData.map((x, i) => ({
                        name: x,
                        value: this.properties.yData[i] || 0
                    }))
                }]
            };
            this.chart.setOption(option, true);
        }
    }

});
